import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import { Row, Col, Form, Input, Button, Card, message } from 'antd';
import DictSelect from 'components/DictSelect';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const { TextArea } = Input;
const FormItem = Form.Item;
const ButtonGroup = Button.Group;
@connect(({ sysNotice, dictionary, loading }) => ({
  sysNotice,
  dictionary,
  submitting: loading.effects['sysNotice/save'],
}))
@Form.create()
export default class SysNoticeEdit extends PureComponent {
  componentDidMount() {
    const {
      dispatch,
      match: { params },
    } = this.props;
    const { opertype, pid } = params;

    if (opertype === 'edit') {
      dispatch({
        type: 'sysNotice/loadDomain',
        payload: pid,
        callback: () => {},
      });
    }

    dispatch({
      type: 'dictionary/loadDict',
      codetype: 'notice.type',
    });
    dispatch({
      type: 'dictionary/loadDict',
      codetype: 'notice.status',
    });
  }

  handleSave = (fields, isNew, editingKey) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysNotice/save',
      payload: {
        ...fields,
        isNew,
        nid: editingKey,
      },
      callback: response => {
        if (response.code === 200) {
          message.success('保存成功');
          dispatch(routerRedux.push('/sys/sysNotice-list'));
        } else {
          message.success('保存失败：[' + response.code + ']' + response.message);
        }
      },
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      form,
      match: { params },
    } = this.props;
    const { opertype, pid } = params;
    let isNew = true;
    if (opertype === 'edit') {
      isNew = false;
    }
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        this.handleSave(fieldsValue, isNew, pid);
      }
    });
  };

  goback = () => {
    history.back();
  };

  render() {
    const {
      submitting,
      form,
      dictionary,
      match: { params },
      sysNotice: { domain },
    } = this.props;
    const { getFieldDecorator } = form;
    const { opertype } = params;
    // let isNew = true;
    let { ntype, title, content, picBanner, createTime, updateTime } = domain;
    if (opertype === 'edit') {
      // isNew = false;
      if (createTime !== undefined && createTime !== null) {
        createTime = moment(createTime, 'yyyy-MM-dd HH:mm:ss');
      }
      if (updateTime !== undefined && updateTime !== null) {
        updateTime = moment(updateTime, 'yyyy-MM-dd HH:mm:ss');
      }
    } else if (opertype === 'add') {
      ntype = '';
      title = '';
      content = '';
      picBanner = '';
      createTime = '';
      updateTime = '';
    }

    const formItemLayout = {
      labelCol: {
        xs: { span: 5 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 15 },
        sm: { span: 15 },
        md: { span: 15 },
        lg: { span: 15 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const action = (
      <Fragment>
        <ButtonGroup>
          <Button icon="rollback" onClick={this.goback}>
            返回
          </Button>
        </ButtonGroup>
      </Fragment>
    );

    return (
      <PageHeaderLayout title="通知管理" content="" action={action}>
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <Row>
              <Col>
                <FormItem {...formItemLayout} label="通知标题">
                  {getFieldDecorator('title', {
                    rules: [{ required: true, message: '请输入通知标题' }],
                    initialValue: title,
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem {...formItemLayout} label="通知banner图">
                  {getFieldDecorator('picBanner', {
                    rules: [{ required: false, message: '请输入通知banner图' }],
                    initialValue: picBanner,
                  })(<Input placeholder="" />)}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem {...formItemLayout} label="通知类型">
                  {form.getFieldDecorator('ntype', {
                    rules: [{ required: true, message: '请输入通知类型（notice.type）' }],
                    initialValue: ntype,
                  })(
                    <DictSelect
                      placeholder="请选择"
                      style={{ width: '100%' }}
                      dictList={dictionary['notice.type']}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col>
                <FormItem {...formItemLayout} label="通知内容">
                  {form.getFieldDecorator('content', {
                    rules: [{ required: true, message: '请输入通知内容' }],
                    initialValue: content,
                  })(<TextArea rows={4} placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24} />
              <Col md={12} sm={24}>
                <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
                  <Button type="primary" htmlType="submit" loading={submitting}>
                    提交
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
